package com.it.travel.service.admin.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.travel.common.ConstEnum;
import com.it.travel.dao.CategoryMapper;
import com.it.travel.dao.CategoryProductMapper;
import com.it.travel.pojo.Category;
import com.it.travel.pojo.CategoryProduct;
import com.it.travel.service.admin.AdminCategoryService;
import com.it.travel.vo.Params.PageParams;
import com.it.travel.vo.Params.admin.AdminCategoryParams;
import com.it.travel.vo.Params.admin.AdminCategoryUpdateParams;
import com.it.travel.vo.Result;
import com.it.travel.vo.admin.AdminCategoryVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Service
public class AdminCategoryServiceImpl implements AdminCategoryService {

    @Resource
    private CategoryMapper categoryMapper;

    @Resource
    private CategoryProductMapper categoryProductMapper;

    @Override
    public Result<?> getInfoPage(PageParams pageParams) {
        String keywords = pageParams.getKeywords();
        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotBlank(keywords)) {  // 如果不为空或null
            System.out.println("keywords = " + keywords);
            wrapper.like(Category::getName, keywords);
        }
        HashMap<String, Object> map = new HashMap<>();
        Page<Category> page = new Page<>(pageParams.getIndex(), pageParams.getSize());
        Page<Category> categoryPage = categoryMapper.selectPage(page, wrapper);
        List<Category> categoryList = categoryPage.getRecords();
        List<AdminCategoryVO> list = new ArrayList<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Category category : categoryList) {
            AdminCategoryVO adminCategoryVO = new AdminCategoryVO();
            BeanUtil.copyProperties(category, adminCategoryVO);
            Date date = new Date(category.getCreateTime());
            adminCategoryVO.setFormatTime(simpleDateFormat.format(date));
            if (category.getParentId() != 0) {
                adminCategoryVO.setLevel("2级");
            } else {
                adminCategoryVO.setLevel("1级");

            }
            list.add(adminCategoryVO);
        }
        map.put("total", categoryPage.getTotal());
        map.put("categoryList", list);
        return Result.success(map, "获取分类数据成功");
    }

    @Override
    public Result<?> save(AdminCategoryParams adminCategoryParams) {
        String name = adminCategoryParams.getName();
        if (adminCategoryParams.getParentId() == null) {
            return Result.error(null, "请选择一级分类");
        }
        if (StringUtils.isNotBlank(name)) {
            Category category = new Category();
            BeanUtil.copyProperties(adminCategoryParams, category);
            category.setCreateTime(System.currentTimeMillis());
            category.setUpdateTime(System.currentTimeMillis());
            category.setParentId(adminCategoryParams.getParentId());
            category.setImg(adminCategoryParams.getImg());
            int i = categoryMapper.insert(category);
            if (i > 0) {
                return Result.success(null, "新增成功");
            }
        }
        return Result.error(null, "新增失败");
    }

    /**
     * 分类id
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public Result<?> delete(Integer id) {  // 如果有其它表要引用这个分类，那为了保证数据一致性要不行级联删除
        int i1 = categoryProductMapper.delete(new QueryWrapper<CategoryProduct>().eq("category_id", id));
        int i = categoryMapper.deleteById(id);
        if (i > 0) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "删除失败");
    }

    @Override
    public Result<?> update(AdminCategoryUpdateParams adminCategoryUpdateParams) {
        String name = adminCategoryUpdateParams.getName();
        if (StringUtils.isNotBlank(name)) {
            Category category = new Category();
            BeanUtil.copyProperties(adminCategoryUpdateParams, category);
            category.setUpdateTime(System.currentTimeMillis());
            categoryMapper.updateById(category);
            return Result.success(null, "修改成功");
        }
        return Result.error(null, "修改失败");
    }

    @Transactional
    @Override
    public Result<?> deletebatch(List<Integer> ids) {
        Integer count = 0;
        for (Integer id : ids) {
            int i = categoryProductMapper.delete(new QueryWrapper<CategoryProduct>().eq("category_id", id));
            count++;
        }
        int i = categoryMapper.deleteBatchIds(ids);
        if (i > 0 && count == ids.size()) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "删除失败");
    }

    @Override
    public Result<?> saveFirstName(String name) {
        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Category::getName, name);
        Category category = categoryMapper.selectOne(wrapper);
        if (category != null) {
            return Result.error(null, "不可重复添加");
        }
        Category category1 = new Category();
        category1.setUpdateTime(System.currentTimeMillis());
        category1.setUpdateTime(System.currentTimeMillis());
        category1.setCreateTime(System.currentTimeMillis());
        category1.setName(name);
        category1.setParentId(ConstEnum.FIRST_PARENTID.getNum());
        int insert = categoryMapper.insert(category1);
        if (insert > 0) {
            return Result.success(null, "删除成功");
        }
        return Result.error(null, "删除失败");


    }

    @Override
    public Result<?> findFirstName() {
        LambdaQueryWrapper<Category> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Category::getParentId, ConstEnum.FIRST_PARENTID.getNum());
        List<Category> list = categoryMapper.selectList(wrapper);
        return Result.success(list, "获取数据成功");
    }
}
